package cn.xinfei.xdecision.data.core.frame.strategy;

import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataException;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class StrategyContext implements BeanPostProcessor {

    private final Map<String, VariableStrategy> variableHandlerMap = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        StrategyHandler annotation = AnnotationUtils.findAnnotation(bean.getClass(), StrategyHandler.class);
        if (ClassUtils.isAssignableValue(VariableStrategy.class, bean)) {
            variableHandlerMap.put(annotation.type().name(), (VariableStrategy) bean);
        }
        return bean;
    }

    public VariableStrategy getStrategy(String type) {
        VariableStrategy variableStrategy = this.variableHandlerMap.get(type);
        if (null == variableStrategy) {
            throw new XDecisionDataException(
                    XDecisionDataExceptionType.DATA_NO_SUCH_STRATEGY_HANDLER_TYPE_ERROR,
                    "没有该类型的策略处理器!"
            );
        }
        return variableStrategy;
    }


}
